<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
require_once BASE_PATH . 'application/controllers/base' . EXT;

class Suscripciones extends Base {

    public function __construct() {
        parent::__construct();
        $this->load->model("suscriptoresDAO");
        $this->load->model("sessionDAO");
        //$this->load->library('email');
        $this->load->library('form_validation');
    }

    public function index() {
        $data = array("title" => "Suscripciones - Newsweek",
            "subtitle" => "",
            "keywords" => "",
            "description" => "",
            "lista" => "",
            "session" => $this->sessionDAO->getUser());

        $this->load->view("header", $data);

        //$this->load->view("menu");

        $susc = array("datos" => $this->suscriptoresDAO->getLevelSuscription(),
            "suscriptor" => $this->suscriptoresDAO->getSuscriber());


        $this->load->view("suscripciones/suscripciones", $susc);

        $this->load->view("footer");
    }

    public function registro() {
        $this->load->view("suscripciones/form-registro");
    }

    public function registropassword($id) {
        $this->load->view("suscripciones/form-registro-password", array("id" => $id));
    }

    public function process() {

        $this->form_validation->set_error_delimiters('<span class="error">', '</span>');

        $this->form_validation->set_rules('name', 'Nombre', 'required');
        //$this->form_validation->set_rules('user', 'UserName', 'trim|required|alpha|min_length[3]|max_length[15]');
        $this->form_validation->set_rules('email', 'E-mail', 'trim|required|valid_email');
        $this->form_validation->set_rules('pass', 'Password', 'required');
        $this->form_validation->set_rules('vpass', 'Password Confirmation', 'required');

        #Mensajes personalizados
        $this->form_validation->set_message('min_length', 'Minimum length for %s is %s characters');
        $this->form_validation->set_message('max_length', 'Maximum length for %s is %s characters');

        if ($this->form_validation->run() != 1) {
            $this->load->view('suscripciones/form-registro');
        } else {
            $this->name = $this->security->xss_clean($this->input->post('name'));
            //$this->user = $this->security->xss_clean($this->input->post('user'));
            $this->email = $this->security->xss_clean($this->input->post('email'));
            $this->pass = $this->security->xss_clean($this->input->post('pass'));
            $this->vpass = $this->security->xss_clean($this->input->post('vpass'));

            $data['name'] = $this->name;
            //$data['user'] = $this->user;
            $data['email'] = $this->email;
            $data['pass'] = $this->pass;
            $data['vpass'] = $this->vpass;
            if ($data['pass'] != $data['vpass']) {
                $data['notsame'] = "<h2>Las contraseñas no coinciden.</h2>";
                $this->load->view('suscripciones/form-registro', $data);
            } else {

                if ($this->suscriptoresDAO->insertNewUser($data)) {
                    $this->load->view('suscripciones/success', $data);
                } else {
                    $data['notsame'] = "<h2>Usuario ya registrado.</h2>";
                    $this->load->view('suscripciones/form-registro', $data);
                }
            }
        }
    }

    public function olvidoPass() {

        $this->form_validation->set_error_delimiters('<span class="error">', '</span>');

        $this->form_validation->set_rules('email', 'E-mail', 'trim|required|valid_email');

        //print_r($this->form_validation->run());die();
        if ($this->form_validation->run() != 1) {
            $this->load->view('suscripciones/passwordolvidado');
        } else {
            $this->email = $this->security->xss_clean($this->input->post('email'));

            $data['email'] = $this->email;
            $tema = "Restaurar contraseña http://revista-ooorale.com.mx/";
            $cuerpo = 'Acceda al siguiente link para restaurar su contraseña<br><a href="http://http://revista-ooorale.com.mx/index.php/home/restaurar/' . md5($data['email']) . '">Click para restaurar contraseña.</a>';
            // Always set content-type when sending HTML email
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type:text/html;charset=utf-8" . "\r\n";
            $headers .= 'From: Ooorale <webmaster@revista-ooorale.com.mx>' . "\r\n";
            if ($this->suscriptoresDAO->findUserByEmail($data['email'])) {
                $randpass = $this->suscriptoresDAO->genRandomString();
                $this->suscriptoresDAO->resetPassword($data['email'], $randpass);
                //se envia correo
                //if($this->SendEmail($data['email'])){
                if (mail($data['email'], $tema, $cuerpo, $headers)) {
                    $data['notification'] = "Tu nueva contraseña se ha enviado a tu correo correctamente!.";
                    $this->load->view('suscripciones/success-reset', $data);
                } else {
                    $data['error'] = "No se pudo enviar el correo, intente nuevamente.";
                    $this->load->view('suscripciones/passwordolvidado', $data);
                }
            } else {
                $data['error'] = "El correo no está registrado.";
                $this->load->view('suscripciones/passwordolvidado', $data);
            }
        }
    }

    public function processPassword() {

        $this->form_validation->set_error_delimiters('<span class="error">', '</span>');

        $this->form_validation->set_rules('pass', 'Password', 'required');
        $this->form_validation->set_rules('vpass', 'Password Confirmation', 'required');

        //print_r($this->form_validation->run());die();
        if ($this->form_validation->run() != 1) {
            $this->load->view('suscripciones/form-registro-password');
        } else {
            $this->pass = $this->security->xss_clean($this->input->post('pass'));
            $this->vpass = $this->security->xss_clean($this->input->post('vpass'));
            $this->id = $this->security->xss_clean($this->input->post('ident'));

            $data['id'] = $this->id;
            $data['password'] = $this->pass;
            $data['vpassword'] = $this->vpass;
            if ($data['password'] != $data['vpassword']) {
                $data['notsame'] = "notsame";
                $this->load->view('suscripciones/form-registro-password', $data);
            } else {
                //print_r($this->suscriptoresDAO->findUserByEmail($data['email']));die();
                //$this->suscriptoresDAO->findUserByid($data['id']);
                //$this->suscriptoresDAO->resetPasswordByid($data['id'],$data['password']);
                //se envia correo
                if ($this->suscriptoresDAO->resetPasswordByid($data['id'], $data['password'])) {
                    $data['notification'] = "Tu contraseña se actualizó correctamente.";
                    $this->load->view('suscripciones/success-reset', $data);
                } else {
                    $this->load->view('suscripciones/form-registro-password', $data);
                }
            }
        }
    }

    public function SendEmail($emaill) {

        $this->load->library('email');
        //$this->email->set_newline("\r\n");
        $this->email->from('webmaster@revista-ooorale.com.mx', 'Ooorale');
        $this->email->to($email);
        $this->email->subject('Restaurar contraseña');
        $this->email->message('Acceda al siguiente link para restaurar su contraseña' . '<br>' . '<a href="http://revista-ooorale.com.mx/index.php/home/restaurar?item=' . md5($emaill) . '">Click aquí para restaurar contraseña.</a>');
        if ($this->email->send()) {
            $this->load->view('contacto/success', $data);
            //echo 'Se ha enviado el mensaje correctamente.';
        } else {
            show_error($this->email->print_debugger());
        }
    }

// function SendEmail

    public function pagar() {
        
    }

    public function pagorealizado() {

        #Obtener parametros
        $payment_status = $_REQUEST['payment_status'];
        $first_name = $_REQUEST['first_name'];
        $item_name = $_REQUEST['item_name'];
        $payment_date = $_REQUEST['payment_date'];
        $transaction_subject = $_REQUEST['transaction_subject'];

        #Asignar valores
        $data = array(
            "payment_status" => $payment_status,
            "first_name" => $first_name,
            "item_name" => $item_name,
            "payment_date" => $payment_date,
            "transaction_subject" => $transaction_subject,
            "address_city" => $_REQUEST['address_city'],
            "address_country" => $_REQUEST['address_country'],
            "address_street" => $_REQUEST['address_street'],
            "address_state" => $_REQUEST['address_state'],
            "address_zip" => $_REQUEST['address_zip'],
            "title" => "Suscripciones",
            "subtitle" => "",
            "keywords" => "",
            "description" => "",
            "lista" => "",
            "session" => $this->sessionDAO->getUser()
        );

        if ($payment_status != "Completed") {
            $this->load->view('suscripciones/payerror', $data);
        } else {
            #Insertar datos en la tabla
            #Etc. etc.
            $this->suscriptoresDAO->insertNewSuscriber($data);
            #Mostrar la vista de pago correcto

            $this->load->view("header", $data);

            $this->load->view("menu");

            $this->load->view('suscripciones/paysucces', $data);

            $this->load->view("footer");
        }
    }

    public function paypal() {

        $data = array("title" => "Suscripciones | Formulario",
            "subtitle" => "",
            "keywords" => "",
            "description" => "",
            "lista" => "",
            "session" => $this->sessionDAO->getUser());

        $this->load->view("header", $data);

        $this->load->view("menu");

        $datos = $this->sessionDAO->getUser();
        $precio = $this->security->xss_clean($this->input->get('precio'));
        $susc = $this->security->xss_clean($this->input->get('susc'));


        #Asginar hosted_button_id
        switch ($susc) {
            case "Trimestral" :
                $hosted_button_id = "SMM77D6EGWR24"; //$195 
                break;
            Case "Semestral" :
                $hosted_button_id = "T6PFDWXSKNCQQ"; //$390
                break;
            case "Anual":
                $hosted_button_id = "N6LR3WZ6BYV34"; //$780
        }

        #Asignar enlace a SandBox o a producción
        $postformpaypal = "https://www.paypal.com/cgi-bin/webscr";
        #$postformpaypal = "https://www.sandbox.paypal.com/cgi-bin/webscr";


        $data = array("data" => $datos,
            "precio" => $precio,
            "susc" => $susc,
            "hosted_button_id" => $hosted_button_id,
            "enlaceformpaypal" => $postformpaypal);

        $this->load->view('suscripciones/susLogin', $data);
    }

    public function links() {

        $user_id = $this->sessionDAO->getUserId();
        $user = $this->suscriptoresDAO->findById($user_id);

        if (count($user) > 0) {

            $data = array("title" => "Suscripciones",
                "subtitle" => "",
                "keywords" => "",
                "description" => "",
                "lista" => "",
                "session" => $this->sessionDAO->getUser());

            $this->load->view("header", $data);

            $this->load->view("menu");


            $level = $this->suscriptoresDAO->getLevelSuscription(array("where" => array("akeebasubs_level_id" => $user->akeebasubs_level_id)));

            $this->load->view('suscripciones/links', array("level" => $level[0]));

            $this->load->view("footer");
        } else {
            $this->index();
        }
    }

}

?>